package com.anhry.app.safety.manage.tjfx.struts.action;

import java.io.ByteArrayOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.anhry.app.safety.manage.tjfx.bean.vo.TjfxCallManageBean;
import com.anhry.app.safety.manage.tjfx.struts.base.ExportExcel;
import com.anhry.app.safety.manage.tjfx.struts.base.TjfxOaBaseAction;
import com.anhry.app.safety.util.Loggers;
import com.anhry.app.safety.util.Page;

@Controller
@Scope("prototype")
@SuppressWarnings("unchecked")
public class TjManageCallAction extends TjfxOaBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	private String key;
//	private String dateFlag;//如果为空，表示点选开始时间和结束时间。不为空，为最近三天、最近一周、最近一月、最近三月、最近半年、本年度之一
	private List<TjfxCallManageBean> resultList;
	private List callList;
	private List gradeList;
	private List excelList; 
	private String pageFlag;
//	private String ids;
	
	/**
	 * 管理部门发送系统提醒统计
	 * @return
	 */
	public String TjManageCall(){
		try {
			int dataCount = initResult();//得到数据库List
				if (callList != null) {
					if (initPageResult(dataCount)) { //得到结果List
						initXmlString(resultList,"系统提醒统计","统计部门","设置次数");//得到页面显示图标xml
					}
				}
				this.setGradeList((List)this.utilService.getHqlQuery("from TbUserGrade g where g.id in (3,4,5,6,7,2,8)"));
				result = "tj_manage_call";
				return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("TjCallAction TjManageCall 出错:"+e);
		}
		return ERROR;
	}
	
	/**
	 * 管理部门接收系统提醒统计
	 * @return
	 */
	public String TjReceiveManageCall(){
		try {
			int dataCount = initReceiveResult();//得到数据库List
				if (callList != null) {
					if (dataCount > 0) {
						if (initPageResult(dataCount)) { //得到结果List
							initXmlString(resultList, "系统提醒统计", "统计部门", "设置次数"); //图表xml
						}
					} else {
						initXmlString(null, "系统提醒统计", "统计部门", "设置次数"); //图表xml
					}
				}			 
				this.setGradeList((List)this.utilService.getHqlQuery("from TbUserGrade g where g.id in (3,4,5,6,7,2,8)"));
				result = "tj_receive_manage_call";
				return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("TjCallAction TjManageCall 出错:"+e);
		}
		return ERROR;
	}
	
	public void initExcel(){
		try {
			List<String> titleList = new ArrayList<String>();
			titleList.add("部门名称");
			int dataCount = 0;
			StringBuffer fileName = new StringBuffer();
			if (pageFlag != null && pageFlag.equals("manageCall")){
				dataCount = initResult();//得到数据库List
				titleList.add("发送数");
				fileName.append("系统提醒发送统计（管理部门）");
			} else if (pageFlag != null && pageFlag.equals("manageReceiveCall")){
				dataCount = initReceiveResult();//得到数据库List
				titleList.add("接收数");
				fileName.append("系统提醒接收统计（管理部门）");
			}
			titleList.add("百分比");
			titleList.add("同比");
			titleList.add("环比");
			
			if (callList != null) {
				initPageResult(dataCount);
			}
			
			ExportExcel export = new ExportExcel(excelList,titleList,fileName.toString());
			HSSFWorkbook workbook = export.createWorkbook();
			
			HttpServletResponse response = this.contextPvd.getResponse();
			response.reset();
			response.setContentType("application/x-msdownload");
			response.addHeader("Content-Disposition", "attachment; filename=\""+new String((fileName.toString()).getBytes("GB2312"),"iso8859-1")+".xls\"");
			ByteArrayOutputStream ostream = new ByteArrayOutputStream();
			ServletOutputStream servletOS = response.getOutputStream();
			workbook.write(ostream);
			servletOS.write(ostream.toByteArray());
			servletOS.flush();
			servletOS.close();
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 初始化数据库查询结果
	 * @return
	 */
	public Integer initReceiveResult(){
		try {
			int rowCount = 0;
			int dataCount = 0;
			StringBuffer hqlString = new StringBuffer("select count(*) from tb_oa_call_msg c  LEFT JOIN tb_user u ON c.adds_user = u.id LEFT JOIN tb_user_grade g ON g.id = u.grade_id LEFT JOIN tb_user_dept d ON d.id = u.dept_id LEFT JOIN tb_user_dept d2 ON d2.id = u.unit_id where u.grade_id not in (0,1) and c.is_dele=0 ");
			initCountParameter(hqlString, "c.msg_time");
			checkSearch(); //处理乱码
			dataCount = Integer.parseInt(this.utilService.getObjectBySql(hqlString.toString()));
			if (dataCount > 0){
				callList = new ArrayList();
				Page page = new Page(setPageSize(10), setPageNum(1), rowCount);
				this.setPage(page);
				hqlString = new StringBuffer("select ");
				initTime(hqlString, "c.msg_time");//初始化时间 参数时间字段
				String groupString = " d.id userid,d.dept_name deptname,d2.id,d2.dept_name unitname FROM tb_oa_call_msg c  LEFT JOIN tb_user u ON c.adds_user = u.id LEFT JOIN tb_user_grade g ON g.id = u.grade_id LEFT JOIN tb_user_dept d ON d.id = u.dept_id LEFT JOIN tb_user_dept d2 ON d2.id = u.unit_id where u.grade_id not in (0,1) and c.is_dele=0 ";
				hqlString.append(groupString).append(initParameter("d.id,d.dept_name,d2.id,d2.dept_name","d.dept_name"));
				callList = (List)this.utilService.getObjectBySql(hqlString.toString(), page.getStartRow(), page.getSize());
				return dataCount;
			}
			return 0;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	/**
	 * 初始化数据库查询结果
	 * @return
	 */
	public Integer initResult(){
		try {
			int rowCount = 0;
			int dataCount = 0;
			StringBuffer hqlString = new StringBuffer("select count(*) from Tb_Oa_Person_Call c LEFT JOIN tb_user u ON c.call_user = u.id LEFT JOIN tb_user_grade g ON g.id = u.grade_id LEFT JOIN tb_user_dept d ON d.id = u.dept_id LEFT JOIN tb_user_dept d2 ON d2.id = u.unit_id where u.grade_id not in (0,1) and c.is_dele=0");
			initCountParameter(hqlString, "c.call_date");
			checkSearch(); //处理乱码
			dataCount = Integer.parseInt(this.utilService.getObjectBySql(hqlString.toString()));
			if (dataCount > 0){
				callList = new ArrayList();
				Page page = new Page(setPageSize(10), setPageNum(1), rowCount);
				this.setPage(page);
				hqlString = new StringBuffer("select ");
				initTime(hqlString, "c.call_date");
				String groupString = " d.id userid,d.dept_name deptname,d2.id,d2.dept_name unit_name FROM tb_oa_person_call c  LEFT JOIN tb_user u ON c.call_user = u.id LEFT JOIN tb_user_grade g ON g.id = u.grade_id LEFT JOIN tb_user_dept d ON d.id = u.dept_id LEFT JOIN tb_user_dept d2 ON d2.id = u.unit_id where u.grade_id not in (0,1) and c.is_dele=0 ";
				hqlString.append(groupString).append(initParameter("d.id,d.dept_name,d2.id,d2.dept_name","d.dept_name"));
				callList = (List)this.utilService.getObjectBySql(hqlString.toString(), page.getStartRow(), page.getSize());
				return dataCount;
			}
			return 0;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 初始化页面返回结果List
	 * @param list 
	 * @param dataCount
	 * @return
	 */
	public boolean initPageResult(Integer dataCount){
		resultList = new ArrayList<TjfxCallManageBean>();
		Object rowList[] ;
		excelList = new ArrayList<Object>();
		TjfxCallManageBean callManageBean;
		Long privateCount;
		if (callList != null){
			for(int i=0; i<callList.size(); i++){
				callManageBean = new TjfxCallManageBean();
				Object[] bean = (Object[])callList.get(i);
				privateCount = Long.parseLong(bean[0]+"");
				callManageBean.setPrivateCount(privateCount);
				callManageBean.setTbCount(bean[1]+"");
				callManageBean.setHbCount(bean[2]+"");
				//市行业判断
				if (bean[3] != null) {
					callManageBean.setShowId("d.id:"+bean[3] + "");
					callManageBean.setShowName(bean[6]+""+bean[4] + "");
				} else {
					callManageBean.setShowId("d2.id:"+bean[5] + "");
					callManageBean.setShowName(bean[6] + "");
				}
				DecimalFormat format = new DecimalFormat("0.00");
				String tempString = format.format((privateCount*1.0/dataCount*1.0)*100);
				callManageBean.setPercent(tempString + "%");
				Integer iString;
				//同比环比
				if (!callManageBean.getTbCount().equals("0") && callManageBean.getTbCount() != null){
					iString = Integer.parseInt(callManageBean.getTbCount());
					tempString = format.format((privateCount*1.0/iString*1.0)*100);
					callManageBean.setTbPercent(tempString+"%");
				} else {
					callManageBean.setTbPercent(format.format(privateCount*100)+"%");
				}
				if (!callManageBean.getHbCount().equals("0") && callManageBean.getHbCount() != null){
					iString = Integer.parseInt(callManageBean.getHbCount());
					tempString = format.format((privateCount*1.0/iString*1.0)*100);
					callManageBean.setHbPercent(tempString+"%");
				} else {
					callManageBean.setHbPercent(format.format(privateCount*100)+"%");
				}
				resultList.add(callManageBean);
				rowList = new Object[5];
				rowList[0]=callManageBean.getShowName();
				rowList[1]=callManageBean.getPrivateCount();
				rowList[2]=callManageBean.getPercent();
				rowList[3]=callManageBean.getTbPercent();
				rowList[4]=callManageBean.getHbPercent();
				excelList.add(rowList);
			}
			callManageBean = new TjfxCallManageBean();
			callManageBean.setShowName("合计");
			callManageBean.setPrivateCount(Long.parseLong(dataCount+""));
			callManageBean.setPercent("--");
			callManageBean.setTbPercent("--");
			callManageBean.setHbPercent("--");
			resultList.add(callManageBean);
			rowList = new Object[5];
			rowList[0]="合计";
			rowList[1]=callManageBean.getPrivateCount();
			rowList[2]="--";
			rowList[3]="--";
			rowList[4]="--";
			excelList.add(rowList);
			return true;
		}
		return false;
	}
	
	
	
	/**
	 * 数据比较生成图表方法
	 * @return
	 */
//	public String compareTj(){
//		if ((null != this.ids && this.ids.length() >0) && ids.split(",").length >1){
//			List<TjfxCallManageBean> tempList = new ArrayList<TjfxCallManageBean>();
//			TjfxCallManageBean bean;
//			for (String deptId:this.ids.split(",")){
//				bean = new TjfxCallManageBean();
//				bean.setShowName(deptId.substring(0, deptId.indexOf(":")));
//				bean.setPrivateCount(Long.parseLong(deptId.substring(deptId.indexOf(";")+1,deptId.length())));
//				tempList.add(bean);
//			}
//			initXmlString(tempList,"","","");
//		} else {
//			tip = "请选择要对比的项";
//		}
//		return SUCCESS; 
//	}
	
	
	
//	public void setTjDate(){
//		//最近三天、最近一周、最近一月、最近三月、最近半年、本年度之一
//		if (!"".equals(dateFlag) && dateFlag != null){
//			Calendar calendar = Calendar.getInstance();
//			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-DD-mm");
//			//如果不是选择的年，则根据前台传过来的日期类型：值字符串设置开始时间
//			//calendar日期类型 1为年，5为日，2为月
//			if (!dateFlag.equals("1")){
//				String dateTypeString = dateFlag.substring(0, 1);//取得时间差类型
//				String dateValueString = dateFlag.substring(2);//取得时间差值
//				calendar.add(Integer.parseInt(dateTypeString), Integer.parseInt(dateValueString));//加减时间
//				beginTime = dateFormat.format(calendar.getTime());
//			} else {
//				//如果选择的是年 从本年第一天开始
//				
//			}
//		}
//	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public List<TjfxCallManageBean> getResultList() {
		return resultList;
	}

	public void setResultList(List<TjfxCallManageBean> resultList) {
		this.resultList = resultList;
	}

	public List getGradeList() {
		return gradeList;
	}

	public void setGradeList(List gradeList) {
		this.gradeList = gradeList;
	}

	public List getExcelList() {
		return excelList;
	}

	public void setExcelList(List excelList) {
		this.excelList = excelList;
	}

	public String getPageFlag() {
		return pageFlag;
	}

	public void setPageFlag(String pageFlag) {
		this.pageFlag = pageFlag;
	}
}
